package com.ihr360.oneclick.controller;

import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.vo.ResultInfo;
import com.ihr360.oneclick.service.SpreadsheetRowService;
import com.ihr360.oneclick.service.WeChatApiService;
import com.ihr360.oneclick.vo.MessageGroupVo;
import com.ihr360.oneclick.vo.StaffMonthMessageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/noauth")
@Api(value = "/noauth", description = "一键工资条系列免登录接口", produces = ("application/json;charset=UTF-8"))
public class NoAuthController {

    private final static Logger logger = LoggerFactory.getLogger(NoAuthController.class);

    @Autowired
    private SpreadsheetRowService spreadsheetRowService;
    @Autowired
    private WeChatApiService weChatApiService;
    @Value("${one.click.notfound}")
    private String notfound;
    @Value("${one.click.validatename}")
    private String validatename;


    @PostMapping("/function/staff/checkName")
    @ApiOperation(value = "/function/staff/checkName", httpMethod = "POST", notes = "校验姓名",
            consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultInfo checkLastName(@RequestParam String functionId, @RequestBody AuthUserInfo authUserInfo) {
        spreadsheetRowService.checLastName(functionId, authUserInfo.getCompanyId(), authUserInfo.getMobileNo(), authUserInfo.getUserName());
        return new ResultInfo.Builder<>().success(true);
    }


    @PostMapping("/function/staff/month/list")
    @ApiOperation(value = "/function/staff/month/list", httpMethod = "POST", notes = "获取用户对于发布数据的所属月份列表",
            consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResultInfo getFunctionDataMonthList(@RequestParam String functionId,
                                                 @RequestBody AuthUserInfo authUserInfo) {
        // 获取oneClick 中的所有月份
        List<String> monthList = weChatApiService.getFunctionStaffDataMonthList(authUserInfo.getCompanyId(), functionId, authUserInfo.getMobileNo());
        // 排序
        Collections.sort(monthList, (o1, o2) -> o1.compareTo(o2));
        List<MessageGroupVo> messageGroupVoList = new ArrayList<>();
        monthList.forEach(monthly -> {
            String[] months = monthly.split("-");
            MessageGroupVo messageGroupVo = new MessageGroupVo();
            messageGroupVo.setYear(months[0]+"年");
            messageGroupVo.setMonth(months[1]+"月");
            messageGroupVo.setGroupId(monthly);
            messageGroupVoList.add(messageGroupVo);
        });
        return new ResultInfo.Builder<>().success(monthList);
    }

    @PostMapping("/function/staff/data")
    @ApiOperation(value = "/function/staff/data", httpMethod = "POST", notes = "获取用户对应发布数据",
            consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResultInfo getFunctionStaffDataByMonth(@RequestParam String functionId,
                                                           @RequestParam String groupId,
                                                           @RequestBody AuthUserInfo authUserInfo) {
        StaffMonthMessageVo staffMonthMessageVo = weChatApiService.getFunctionStaffDataByMonth(authUserInfo.getCompanyId(), functionId, authUserInfo.getMobileNo(), groupId);
        if(staffMonthMessageVo == null){
            staffMonthMessageVo = new StaffMonthMessageVo();
            staffMonthMessageVo.setMonth(groupId);
            staffMonthMessageVo.setBatchMessageList(new ArrayList<>());
        }
        return new ResultInfo.Builder<>().success(staffMonthMessageVo);
    }


    @GetMapping("/getFunctionDataIdList")
    @ApiOperation(value = "/getFunctionDataIdList", httpMethod = "GET", response = Boolean.class)
    public void getFunctionDataIdList(@RequestParam String spreadSheetRowId, @RequestParam String userName, HttpServletResponse response) {
        String one_click_view_template = spreadsheetRowService.getSpreadSheetRowById(spreadSheetRowId, userName);
        logger.info(one_click_view_template);
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //response.setContentType("text/html;charset=UTF-8");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(one_click_view_template.getBytes("UTF-8"));
            //outputStream.println(one_click_view_template);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error("页面模板输出失败", e);
        }
    }


    @GetMapping("/checkSpreadsheetRowIsPublish")
    @ApiOperation(value = "/checkSpreadsheetRowIsPublish", httpMethod = "GET", response = Boolean.class)
    public void checkSpreadsheetRowIsPublish(@RequestParam String spreadSheetRowId , HttpServletResponse response) throws IOException {
        Boolean result = spreadsheetRowService.checkSpreadsheetRowIsPublish(spreadSheetRowId);
        if (result) {
            response.sendRedirect(validatename + spreadSheetRowId);
        } else {
            response.sendRedirect(notfound);
        }
    }
}
